#include "SqlAccess.h"
#include "ConfigFile.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

static int errorNum;                  //错误代号
static const char* errorInfo;         //错误提示

//向表中添加数据
int insertInto(MYSQL *mysql , const char* tbName, const char* colName, const char* content) 
{
	if(NULL==mysql || NULL==tbName || NULL==colName || NULL==content)
	{
		WriteFileLog(LERROR, "向表中添加数据失败 ，参数为空 ！");
		return -1;
	}
 //WriteFileLog(LERROR, "队列输出66666666666666666666666666666！");

	char query[15000];
	memset(query,0,15000);
	sprintf(query,"insert into %s (%s) values (%s)",tbName, colName, content);
 //WriteFileLog(LERROR, "队列输出777777777777777777777777777777777！");

	if (0 == mysql_query(mysql, query))
		return 0;
	else
	{
		errorIntoMySQL(mysql);
		WriteFileLog(LERROR, "添加数据失败，错误号：%d, 错误信息：%s ！", errorNum, errorInfo);
		return -1;
	}
}

//向表中添加GpsDataStruct类型数据
int insertGpsDataStruct(MYSQL *mysql,GpsDataStruct* gds)    
{
	if(NULL == gds || NULL == mysql)
	{
		WriteFileLog(LERROR, "向表中添加GpsDataStruct类型数据失败，参数为空 ！");
		return -1;
	}
	if(!strcmp(gds->czName,""))
		sprintf(gds->czName,"-1");
	if(!strcmp(gds->czTime,"")){
time_t timeReal;
time(&timeReal);
timeReal = timeReal +8*3600;
struct tm* t = gmtime(&timeReal);
sprintf(gds->czTime,"%4d-%02d-%02d %02d:%02d:%02d",t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec);
}
		
	if(!strcmp(gds->czLatitude,""))
		sprintf(gds->czLatitude,"-1");
	if(!strcmp(gds->czLatitudeH,""))
		sprintf(gds->czLatitudeH,"/");
	if(!strcmp(gds->czLongitude,""))
		sprintf(gds->czLongitude,"-1");
	if(!strcmp(gds->czLongitudeH,""))
		sprintf(gds->czLongitudeH,"/");
	if(!strcmp(gds->czSpeed,""))
		sprintf(gds->czSpeed,"-1");
	if(!strcmp(gds->czCourse,""))
		sprintf(gds->czCourse,"-1");
	//if(!strcmp(gds->czMileage,""))
		sprintf(gds->czMileage,"-1");
	char t1[50] = {"gpsdata"};
	char t2[500] = {"clientId, matchId, time, latitude, latitudeHemisphere, longitude, longitudeHemisphere, speed, course, mileage"};
	char t3[500];
	memset(t3,0,500);
	sprintf(t3, "'%s', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s'",
		gds->czName, 1, gds->czTime, gds->czLatitude, gds->czLatitudeH, gds->czLongitude, gds->czLongitudeH,
		gds->czSpeed, gds->czCourse, gds->czMileage);
	if (!insertInto(mysql, t1, t2, t3))
		return 0;
	else
		//WriteFileLog(LERROR, "添加数据失败，错误号：%d, 错误信息：%s ！", errorNum, errorInfo);
		return -1;	
}

//向clienttable插入数据
int insert2Clienttable(MYSQL* mysql, const char* cName)
{
	if(NULL == mysql || NULL == cName)
	{
		WriteFileLog(LERROR, "向clienttable插入数据失败，参数为空！");
		return -1;
	}
	char t1[50] = {"clienttable"};
	char t2[500] = {"clientName, clientIP, boatId, boatName, matchId, matchName"};
	char t3[500];
	memset(t3,0,500);
	unsigned short bid = 1;
	char bname[50] = {"boat1"};
	char clientip[50] = {"192.168.1.1"};
	sprintf(t3,"'%s', '%s', '%d', '%s', '%d', '%s'",cName,clientip,bid,bname,matchId,matchName);
	if(!insertInto(mysql, t1,t2,t3))
		return 0;
	else
		return -1;
}

//向matchtable插入数据
int insert2Matchtable(MYSQL* mysql, const char* cName)
{
	if(NULL == mysql || NULL == cName)
	{
		WriteFileLog(LERROR, "向matchtable插入数据失败，参数为空！");
		return -1;
	}
	char t1[20] = {"matchtable"};
	char t2[200] = {"matchName"};
	char t3[200];
	memset(t3,0,200);
	sprintf(t3,"'%s'",cName);
	if(!insertInto(mysql, t1,t2,t3))
		return 0;
	else
		return -1;
}

//获取比赛ID，如果记录不存在，则插入新纪录
int GetIdWithMatchName(MYSQL* mysql, const char* matchname )
{
	if(NULL == matchname || !strcmp(matchname,""))
		return -1;
	char s_str[500];
	memset(s_str,0,500);
	MYSQL_RES *result;
	
	sprintf(s_str,"select ID from matchtable where matchName = '%s'",matchname);

	if (0 != mysql_query(mysql, s_str)) 
	{
		errorIntoMySQL(mysql);
		WriteFileLog(LERROR, "获取客户端对应id 查询失败，错误号：%d, 错误信息：%s ！", errorNum, errorInfo);
		return -1;
	}
 
	//查询成功，保存查询结果
	result = mysql_store_result(mysql);
	if(NULL == result)
	{
		errorIntoMySQL(mysql);
		WriteFileLog(LERROR, "获取客户端对应id 保存结果失败，错误号：%d, 错误信息：%s ！", errorNum, errorInfo);
		//返回错误
		return -1;
	}

	//获取查询出来的结果
	MYSQL_ROW row; //保存行记录信息
	unsigned int i;
	 
	row = mysql_fetch_row(result);
	if(NULL == row)   //未找到该比赛
	{
		//比赛信息插入matchtable表，并返回对应id
		if(!insert2Matchtable(mysql, matchname))
		{
			//添加信息成功返回对应id
			mysql_free_result(result);
			return GetIdWithMatchName(mysql, matchname);
		}
		else
		{
			//添加失败
			mysql_free_result(result);
			WriteFileLog(LERROR, "尝试插入未找到的比赛记录时失败！");
			return -1;
		}
	}
	else
	{
		//找到对应id，返回id号
		mysql_free_result(result);
		return atoi(row[0]);
	}
	mysql_free_result(result);
	return -1;
}

//使用客户端名获取对应id，如表中不存在则插入该客户端
int GetIdWithClientName(MYSQL* mysql, const char* clientname )
{
	if(NULL == clientname || !strcmp(clientname,""))
		return -1;
	char s_str[500];
	memset(s_str,0,500);
	MYSQL_RES *result;
	
	sprintf(s_str,"select id from clienttable where clientName = '%s' and matchId = %d",clientname, matchId);
	//sprintf(s_str,"select id from clienttable where clientName = '%s'",clientname);

	if (0 != mysql_query(mysql, s_str)) 
	{
		errorIntoMySQL(mysql);
		WriteFileLog(LERROR, "获取客户端对应id 查询失败，错误号：%d, 错误信息：%s ！", errorNum, errorInfo);
		return -1;
	}
 
	//查询成功，保存查询结果
	result = mysql_store_result(mysql);
	if(NULL == result)
	{
		errorIntoMySQL(mysql);
		WriteFileLog(LERROR, "获取客户端对应id 保存结果失败，错误号：%d, 错误信息：%s ！", errorNum, errorInfo);
		//返回错误
		return -1;
	}

	//获取查询出来的结果
	MYSQL_ROW row; //保存行记录信息
	unsigned int i;
	 
	row = mysql_fetch_row(result);
	if(NULL == row)   //未找到该终端
	{
		//终端信息插入clienttable表，并返回对应id
		if(!insert2Clienttable(mysql, clientname))
		{
			//添加信息成功返回对应id
			mysql_free_result(result);
			return GetIdWithClientName(mysql, clientname);
		}
		else
		{
			//添加失败
			mysql_free_result(result);
			WriteFileLog(LERROR, "尝试插入未找到的客户端时失败！");
			return -1;
		}
	}
	else
	{
		//找到对应id，返回id号
		mysql_free_result(result);
		return atoi(row[0]);
	}
	mysql_free_result(result);
	return -1;
}

//将gpsdata队列数据拼接处理后存入表中
int insertGpsDataGroup(MYSQL* mysql, GpsDataStruct** gdsArray, int lens)
{
	if(NULL == mysql || NULL == gdsArray || lens<=0)
	{
		WriteFileLog(LERROR, "gpsdata队列数据拼接处理存入表中失败, 传参异常！");
		return -1;
	}
	char latitude[2000];
	char latitudeH[1000];
	char longitude[2000];
	char longitudeH[1000];
	char speed[2000];
	char course[2000];
	char mileage[2000];
	memset(latitude,0,2000);
	memset(latitudeH,0,1000);
	memset(longitude,0,2000);
	memset(longitudeH,0,1000);
	memset(speed,0,2000);
	memset(course,0,2000);
	memset(mileage,0,2000);
	int Id = -1;
	int i = 0;
	int count = 0;//有效数据计数
	GpsDataStruct* temp = NULL;
time_t timeReal;
time(&timeReal);
timeReal = timeReal +8*3600;
struct tm* t = gmtime(&timeReal);

	for(i;i<lens;i++)
	{
		temp = gdsArray[i];
		if(NULL == temp)
			return -2;
		if(!strcmp(temp->czName,""))
			sprintf(temp->czName,"-1");
		if(!strcmp(temp->czTime,""))
			//sprintf(temp->czTime,"1900-01-01 00:00:00");
sprintf(temp->czTime,"%4d-%02d-%02d %02d:%02d:%02d",t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec);
/*if(!strcmp(temp->czLatitude,"")||!strcmp(temp->czLatitude," ")){
	//无效数据
	free(temp);
	temp = NULL;
	continue;
}
count++;*/
		if(!strcmp(temp->czLatitude,""))
			sprintf(temp->czLatitude,"-1");
		if(!strcmp(temp->czLatitudeH,""))
			sprintf(temp->czLatitudeH,"/");
		if(!strcmp(temp->czLongitude,""))
			sprintf(temp->czLongitude,"-1");
		if(!strcmp(temp->czLongitudeH,""))
			sprintf(temp->czLongitudeH,"/");
		if(!strcmp(temp->czSpeed,""))
			sprintf(temp->czSpeed,"-1");
		if(!strcmp(temp->czCourse,""))
			sprintf(temp->czCourse,"-1");
		if(!strcmp(temp->czMileage,""))
			sprintf(temp->czMileage,"1");
		Id = GetIdWithClientName(mysql, temp->czName);
		sprintf(latitude,"%s%d:%s;",latitude,Id,temp->czLatitude);
		sprintf(latitudeH,"%s%d:%s;",latitudeH,Id,temp->czLatitudeH);
		sprintf(longitude,"%s%d:%s;",longitude,Id,temp->czLongitude);
		sprintf(longitudeH,"%s%d:%s;",longitudeH,Id,temp->czLongitudeH);
		sprintf(speed,"%s%d:%s;",speed,Id,temp->czSpeed);
		sprintf(course,"%s%d:%s;",course,Id,temp->czCourse);
		snprintf(mileage,2000,"%s%d:%s;",mileage,Id,temp->czMileage);		
		free(temp);
		temp = NULL;
	}
//if(count == 0)return -4;
	char _time[50];
	//sprintf(_time,"1900-01-01 00:00:00");
sprintf(_time,"%4d-%02d-%02d %02d:%02d:%02d",t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec);
	char _name[20] = {"2"};
	char t1[50] = {"gpsdata"};
	char t2[500] = {"clientId, matchId, time, latitude, latitudeHemisphere, longitude, longitudeHemisphere, speed, course, mileage"};
	char t3[14000];
	memset(t3,0,14000);
	char ttt[50] = {"1"};
	sprintf(t3,"'%s', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s'",_name,matchId,_time,latitude,latitudeH,longitude,longitudeH,speed,course,ttt);
	if (!insertInto(mysql, t1, t2, t3))
		return 0;
	else
		return -3;	
}

//获取错误信息
void errorIntoMySQL(MYSQL *mysql)
{
	if(NULL == mysql)
	{
		WriteFileLog(LERROR, "获取错误信息失败，参数为空 ！");
		return;
	}
	errorNum = mysql_errno(mysql);
	errorInfo = mysql_error(mysql);
}



